<template>
  <!-- 自定义导航栏: 默认透明不可见, scroll-view 滚动到 50 时展示 -->
  <skeleton v-if="showSkeleton"></skeleton>
  <view v-else>
    <view
      class="navbar"
      :style="{
        paddingTop: safeAreaInsets?.top + 'px',
        backgroundColor: showNav ? '#f8f8f8' : 'transparent',
      }"
    >
      <view class="wrap">
        <navigator
          v-if="pages.length > 1"
          open-type="navigateBack"
          class="back icon-left"
          :style="{ color: showNav ? '#000' : '#fff' }"
        ></navigator>
        <navigator
          v-else
          url="/pages/index/index"
          open-type="switchTab"
          class="back icon-home"
          :style="{ color: showNav ? '#000' : '#fff' }"
        >
        </navigator>
        <view class="title" :style="{ color: showNav ? '#000' : 'transparent' }">订单详情</view>
      </view>
    </view>
    <scroll-view
      scroll-y
      class="viewport"
      id="scroller"
      @scrolltolower="onScrolltolower"
      @scroll="onScroll"
    >
      <template>
        <!-- 订单状态 -->
        <view class="overview" :style="{ paddingTop: safeAreaInsets!.top + 20 + 'px' }">
          <!-- 待付款状态:展示去支付按钮和倒计时 -->
          <template v-if="orderDetailData.orderState === 1">
            <view class="status icon-clock">等待付款</view>
            <view class="tips">
              <text class="money"
                >应付金额: ¥ {{ parseFloat(orderDetailData.payMoney).toFixed(2) }}</text
              >
              <text class="time">支付剩余: {{ times }}</text>
            </view>
            <view class="button" @click="goPayment">去支付</view>
          </template>
          <!-- 其他订单状态:展示再次购买按钮 -->
          <template v-else>
            <!-- 订单状态文字 -->
            <view class="status"> {{ orderState }} </view>
            <view class="button-group">
              <navigator
                class="button"
                :url="`/pagesOrder/create/create?orderId=${query.id}`"
                hover-class="none"
              >
                再次购买
              </navigator>
              <!-- 待发货状态：模拟发货,开发期间使用,用于修改订单状态为已发货 -->
              <view v-if="orderDetailData.orderState === 2" class="button" @click="deliverGoods">
                模拟发货
              </view>
            </view>
          </template>
        </view>
        <!-- 配送状态 -->
        <view class="shipment">
          <!-- 订单物流信息 -->
          <view
            v-if="orderDetailData.orderState > 2 && orderDetailData.orderState < 6"
            class="item icon"
            @click="lookDetails"
          >
            <view class="message">
              {{ logInfo.text }}
            </view>
            <view class="date">
              {{ logInfo.time }}
            </view>
          </view>
          <!-- 用户收货地址 -->
          <view class="locate">
            <view class="user">{{
              orderDetailData.receiverContact + ' ' + orderDetailData.receiverMobile
            }}</view>
            <view class="address">{{ orderDetailData.receiverAddress }}</view>
            <view class="date"> {{ orderDetailData.createTime }}</view>
          </view>
        </view>

        <!-- 商品信息 -->
        <view class="goods">
          <view class="item">
            <navigator
              class="navigator"
              v-for="item in orderDetailData.skus"
              :key="item.id"
              :url="`/pages/goodsDetail/goodsDetail?id=${item.spuId}`"
              hover-class="none"
            >
              <image class="cover" :src="item.image"></image>
              <view class="meta">
                <view class="name ellipsis">{{ item.name }}</view>
                <view class="type">{{ item.attrsText }}</view>
                <view class="price">
                  <view class="actual">
                    <text class="symbol">¥</text>
                    <text>{{ item.curPrice.toFixed(2) }}</text>
                  </view>
                </view>
                <view class="quantity">x{{ item.quantity }}</view>
              </view>
            </navigator>
            <!-- 待评价状态:展示按钮 -->
            <view class="action" v-if="orderDetailData.orderState === 4">
              <view class="button primary">申请售后</view>
              <navigator url="" class="button"> 去评价 </navigator>
            </view>
          </view>
          <!-- 合计 -->
          <view class="total">
            <view class="row">
              <view class="text">商品总价: </view>
              <view class="symbol">{{ parseFloat(orderDetailData.totalMoney).toFixed(2) }}</view>
            </view>
            <view class="row">
              <view class="text">运费: </view>
              <view class="symbol">{{
                parseFloat(String(orderDetailData.postFee)).toFixed(2)
              }}</view>
            </view>
            <view class="row">
              <view class="text">应付金额: </view>
              <view class="symbol primary">{{
                parseFloat(orderDetailData.payMoney).toFixed(2)
              }}</view>
            </view>
          </view>
        </view>

        <!-- 订单信息 -->
        <view class="detail">
          <view class="title">订单信息</view>
          <view class="row">
            <view class="item">
              订单编号: {{ query.id }} <text class="copy" @click="copyOrderId">复制</text>
            </view>
            <view class="item">下单时间: {{ orderDetailData.createTime }}</view>
          </view>
        </view>

        <!-- 猜你喜欢 -->
        <tphGuess ref="tphGuessRef" />

        <!-- 底部操作栏 -->
        <view
          class="toolbar-height"
          :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
        ></view>
        <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
          <!-- 待付款状态:展示支付按钮 -->
          <template v-if="orderDetailData.orderState === 1">
            <view class="button primary" @click="goPayment"> 去支付 </view>
            <view class="button" @click="popup?.open?.()"> 取消订单 </view>
          </template>
          <!-- 其他订单状态:按需展示按钮 -->
          <template v-else>
            <navigator
              class="button secondary"
              :url="`/pagesOrder/create/create?orderId=${query.id}`"
              hover-class="none"
            >
              再次购买
            </navigator>
            <!-- 待收货状态: 展示确认收货 -->
            <view
              class="button primary"
              v-if="orderDetailData.orderState === 3"
              @click="ConfirmReceipt"
            >
              确认收货
            </view>
            <!-- 待评价状态: 展示去评价 -->
            <view class="button" v-if="orderDetailData.orderState === 4"> 去评价 </view>
            <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
            <view class="button delete" v-if="orderDetailData.orderState >= 4" @click="deleteOrder">
              删除订单
            </view>
          </template>
        </view>
      </template>
    </scroll-view>
  </view>
  <!-- 取消订单弹窗 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <view class="popup-root">
      <view class="title">订单取消</view>
      <view class="description">
        <view class="tips">请选择取消订单的原因：</view>
        <view class="cell" v-for="item in reasonList" :key="item" @tap="reason = item">
          <text class="text">{{ item }}</text>
          <text class="icon" :class="{ checked: item === reason }"></text>
        </view>
      </view>
      <view class="footer">
        <view class="button" @tap="popup?.close?.()">取消</view>
        <view class="button primary" @click="cancelOrder">确认</view>
      </view>
    </view>
  </uni-popup>
  <!-- 物流详情弹窗 -->
  <logisticsDetailsPopup ref="logisticsDetailsPopupRef"></logisticsDetailsPopup>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import {
  getOrderDetailAPI,
  cancelOrderAPI,
  getWxPayAPI,
  getMockPayAPI,
  getDeliverGoodsAPI,
  getOrderLogisticsAPI,
  putConfirmReceiptAPI,
  deleteOrderAPI,
} from '@/api/order'
import type { orderDetailType, orderLogisticsType, logisticsType } from '@/types/order'
import logisticsDetailsPopup from './components/logisticsDetailsPopup.vue'
import skeleton from './components/skeleton.vue'

const showSkeleton = ref(true)
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取页面栈
const pages = getCurrentPages()
// 是否显示自定义导航栏
const showNav = ref(false)
// 弹出层组件
const popup = ref()
// 取消原因列表
const reasonList = ref([
  '商品无货',
  '不想要了',
  '商品信息填错了',
  '地址信息填写错误',
  '商品降价',
  '其它',
])
// 订单取消原因
const reason = ref('')
// 获取页面参数
const query = defineProps<{
  id: string
}>()
// 猜你喜欢的red对象
const tphGuessRef = ref()
// 滚动到底部的回调
const onScrolltolower = () => {
  tphGuessRef.value.scrolltolower()
}
// 页面滚动的回调
const onScroll = (e: any) => {
  if (e.detail.scrollTop >= 100) {
    // 显示自定义导航栏
    showNav.value = true
  } else {
    showNav.value = false
  }
}
// 订单详情
const orderDetailData = ref<orderDetailType>({} as orderDetailType)
// 获取订单详情的函数
const getOrderDetailData = async () => {
  const res = await getOrderDetailAPI(query.id)
  if (res.code === '1') {
    orderDetailData.value = res.result
    if (
      orderDetailData.value.orderState === 3 ||
      orderDetailData.value.orderState === 4 ||
      orderDetailData.value.orderState === 5
    ) {
      // 获取物流信息
      getOrderLogisticsData()
    }
    if (orderDetailData.value.countdown > 0 && orderDetailData.value.orderState === 1) {
      const timer = setInterval(() => {
        orderDetailData.value.countdown -= 1
        if (orderDetailData.value.countdown <= 0) {
          cancelOrder()
          clearInterval(timer)
        }
      }, 1000)
    }
  }
}
// 计算出时分秒
const times = computed(() => {
  // 计算出时
  let h: string | number = Math.floor(orderDetailData.value.countdown / 60 / 60)
  h = h < 10 ? '0' + h : h
  // 计算出分
  let m: string | number = Math.floor((orderDetailData.value.countdown / 60) % 60)
  m = m < 10 ? '0' + m : m
  // 计算出秒
  let s: string | number = Math.floor(orderDetailData.value.countdown % 60)
  s = s < 10 ? '0' + s : s
  return h + ' 时 ' + m + ' 分 ' + s + ' 秒'
})
// 计算出支付后订单显示的状态
const orderState = computed(() => {
  switch (orderDetailData.value.orderState) {
    case 2:
      return '待发货'
    case 3:
      return '待收货'
    case 4:
      return '待评价'
    case 5:
      return '已完成'
    case 6:
      return '已取消'
    default:
      return '待付款'
  }
})
// 取消订单
const cancelOrder = async () => {
  const res = await cancelOrderAPI(query.id, reason.value)
  if (res.code === '1') {
    orderDetailData.value = res.result
  }
  uni.showToast({
    title: '取消订单成功',
    icon: 'success',
  })
  // 关闭弹出层
  popup.value!.close()
}
// 支付按钮的回调
const goPayment = async () => {
  if (import.meta.env.DEV) {
    // 开发环境
    // 调用模拟支付的接口
    const res = await getMockPayAPI(query.id)
    if (res.code === '1') {
      // 支付成功,跳转到支付结果页
      uni.redirectTo({
        url: `/pagesOrder/payment/payment?id=${query.id}`,
      })
    }
  } else {
    // 生产环境
    // 调用微信支付的接口
    const res = await getWxPayAPI(query.id)
    // 弹出支付
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: '',
      ...res.result,
      success: (result) => {},
      fail: (error) => {},
    })
  }
}
// 模拟发货
const deliverGoods = async () => {
  // 调用接口
  const res = await getDeliverGoodsAPI(query.id)
  if (res.code === '1') {
    // 发货成功
    uni.showToast({
      title: '发货成功',
      icon: 'success',
    })
    // 更新订单状态
    getOrderDetailData()
  }
}
// 物流信息
const logisticsList = ref<orderLogisticsType>({} as orderLogisticsType)
// 最新的物流日志
const logInfo = ref<logisticsType>({} as logisticsType)
// 获取物流信息的函数
const getOrderLogisticsData = async () => {
  const res = await getOrderLogisticsAPI(query.id)
  if (res.code === '1') {
    logisticsList.value = res.result
    logInfo.value = logisticsList.value.list[0] || {}
  }
}
// 物流详情弹出层的ref对象
const logisticsDetailsPopupRef = ref()
// 点击物流信息的回调
const lookDetails = () => {
  // 将物流日志传过去
  const data = logisticsList.value.list || []
  // 整合用户地址，传过去
  const userAddresses = {
    receiverContact: orderDetailData.value.receiverContact,
    receiverMobile: orderDetailData.value.receiverMobile,
    receiverAddress: orderDetailData.value.receiverAddress,
    createTime: orderDetailData.value.createTime,
  }
  logisticsDetailsPopupRef.value?.open(data, userAddresses)
}
// 确认收货按钮的回调
const ConfirmReceipt = () => {
  uni.showModal({
    title: '是否确认签收?',
    showCancel: true,
    success: async ({ confirm }) => {
      if (confirm) {
        // 确认签收
        const res = await putConfirmReceiptAPI(query.id)
        if (res.code === '1') {
          uni.showToast({
            title: '确认收货成功',
            icon: 'success',
            mask: true,
          })
          orderDetailData.value = res.result
        }
      }
    },
  })
}
// 删除订单按钮的回调
const deleteOrder = () => {
  // 二次询问用户
  uni.showModal({
    title: '是否删除订单?',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        const res = await deleteOrderAPI([query.id])
        if (res.code === '1') {
          // 提示用户删除成功
          uni.showToast({
            title: '删除成功',
            icon: 'success',
          })
          setTimeout(() => {
            // 判断是否有上一页，有的话返回上一页，没有返回首页
            if (pages.length > 1) {
              uni.navigateBack()
            } else {
              uni.switchTab({
                url: '/pages/index/index',
              })
            }
          }, 300)
        }
      }
    },
  })
}
// 复制按钮的回调
const copyOrderId = () => {
  uni.setClipboardData({
    data: query.id,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success',
        mask: true,
      })
    },
  })
}
onShow(async () => {
  showSkeleton.value = true
  await Promise.all([getOrderDetailData()])
  showSkeleton.value = false
})
</script>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.navbar {
  width: 750rpx;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  // background-color: #f8f8f8;
  background-color: transparent;

  .wrap {
    position: relative;

    .title {
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      // color: #000;
      color: transparent;
    }

    .back {
      position: absolute;
      left: 0;
      height: 44px;
      width: 44px;
      font-size: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      // color: #000;
      color: #fff;
    }
  }
}

.viewport {
  flex: 1;
  overflow-y: scroll;
  background-color: #f7f7f8;
}

.overview {
  display: flex;
  flex-direction: column;
  align-items: center;

  line-height: 1;
  padding-bottom: 30rpx;
  color: #fff;
  background: url(../../static/images/center_bg.jpg);
  background-size: cover;

  .status {
    font-size: 36rpx;
  }

  .status::before {
    margin-right: 6rpx;
    font-weight: 500;
  }

  .tips {
    margin: 30rpx 0;
    display: flex;
    font-size: 14px;
    align-items: center;

    .money {
      margin-right: 30rpx;
    }
  }

  .button-group {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .button {
    width: 260rpx;
    height: 64rpx;
    margin: 0 10rpx;
    text-align: center;
    line-height: 64rpx;
    font-size: 28rpx;
    color: #ff3304;
    border-radius: 68rpx;
    background-color: #fff;
  }
}
.shipment {
  line-height: 1.4;
  padding: 0 20rpx;
  margin: 20rpx 20rpx 0;
  border-radius: 10rpx;
  background-color: #fff;

  .locate,
  .item {
    min-height: 120rpx;
    padding: 30rpx 30rpx 25rpx 75rpx;
    background-size: 50rpx;
    background-repeat: no-repeat;
    background-position: 6rpx center;
  }

  .locate {
    background-image: url(../../static/images/address.png);

    .user {
      font-size: 26rpx;
      color: #444;
    }

    .address {
      font-size: 24rpx;
      color: #666;
    }
  }

  .item {
    background-image: url(../../static/images/bigCar.png);
    border-bottom: 1rpx solid #eee;
    position: relative;

    .message {
      height: 70rpx;
      font-size: 26rpx;
      color: #ff3304;
    }
  }
  .icon::after {
    position: absolute;
    top: 28rpx;
    right: 0;
    font-size: 26rpx;
    color: #ff3304;
    font-family: 'iconfont';
    content: '详细信息\e612';
  }
}
.date {
  font-size: 24rpx;
  color: #666;
}

.goods {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;

    .navigator {
      display: flex;
      margin: 20rpx 0;
    }

    .cover {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      display: flex;
      margin-top: 6rpx;
      font-size: 24rpx;
    }

    .symbol {
      font-size: 20rpx;
    }

    .original {
      color: #999;
      text-decoration: line-through;
    }

    .actual {
      margin-left: 10rpx;
      color: #444;
    }

    .text {
      font-size: 22rpx;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 24rpx;
      color: #444;
    }

    .action {
      display: flex;
      flex-direction: row-reverse;
      justify-content: flex-start;
      padding: 30rpx 0 0;

      .button {
        width: 200rpx;
        height: 60rpx;
        text-align: center;
        justify-content: center;
        line-height: 60rpx;
        margin-left: 20rpx;
        border-radius: 60rpx;
        border: 1rpx solid #ccc;
        font-size: 26rpx;
        color: #444;
      }

      .primary {
        color: #ff3304;
        border-color: #ff3304;
      }
    }
  }

  .total {
    line-height: 1;
    font-size: 26rpx;
    padding: 20rpx 0;
    color: #666;

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10rpx 0;
    }

    .symbol::before {
      content: '¥';
      font-size: 80%;
      margin-right: 3rpx;
    }

    .primary {
      color: #cf4444;
      font-size: 36rpx;
    }
  }
}

.detail {
  line-height: 1;
  padding: 30rpx 20rpx 0;
  margin: 20rpx 20rpx 0;
  font-size: 26rpx;
  color: #666;
  border-radius: 10rpx;
  background-color: #fff;

  .title {
    font-size: 30rpx;
    color: #444;
  }

  .row {
    padding: 20rpx 0;

    .item {
      padding: 10rpx 0;
      display: flex;
      align-items: center;
    }

    .copy {
      border-radius: 20rpx;
      font-size: 20rpx;
      border: 1px solid #ccc;
      padding: 5rpx 10rpx;
      margin-left: 10rpx;
    }
  }
}

.toolbar-height {
  height: 100rpx;
  box-sizing: content-box;
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .button {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 200rpx;
    height: 72rpx;
    margin-left: 15rpx;
    font-size: 26rpx;
    border-radius: 72rpx;
    border: 1rpx solid #ccc;
    color: #444;
  }

  .delete {
    order: 4;
  }

  .button {
    order: 3;
  }

  .secondary {
    order: 2;
    color: #ff3304;
    border-color: #ff3304;
  }

  .primary {
    order: 1;
    color: #fff;
    background-color: #ff3304;
  }
}

.popup-root {
  padding: 30rpx 30rpx 0;
  border-radius: 10rpx 10rpx 0 0;
  overflow: hidden;

  .title {
    font-size: 30rpx;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .description {
    font-size: 28rpx;
    padding: 0 20rpx;

    .tips {
      color: #444;
      margin-bottom: 12rpx;
    }

    .cell {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 0;
      color: #666;
    }

    .icon::before {
      content: '\e633';
      font-family: 'iconfont' !important;
      font-size: 38rpx;
      color: #999;
    }

    .icon.checked::before {
      content: '\e6c1';
      font-size: 38rpx;
      color: #ff3304;
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0 40rpx;
    font-size: 28rpx;
    color: #444;

    .button {
      flex: 1;
      height: 72rpx;
      text-align: center;
      line-height: 72rpx;
      margin: 0 20rpx;
      color: #444;
      border-radius: 72rpx;
      border: 1rpx solid #ccc;
    }

    .primary {
      color: #fff;
      background-color: #ff3304;
      border: none;
    }
  }
}
</style>
